<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : JwtAuthModelTrait.php
 * Created on : 2020-7-25 10:39:25
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace haoteam\traits;

use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;
use think\facade\Config;
use UnexpectedValueException;
use haoteam\service\SessionService;

/**
 * 
 * Class JwtAuthModelTrait
 * Tiger <1192851302@qq.com> 2020-7-25 10:39:25
 */
trait JwtAuthModelTrait {

    /**
     * @param string $type
     * @param array $params
     * @return array
     */
    public function getToken(string $type, array $params = []): array {
        $id = $this->{$this->getPk()};
        $host = app()->request->host();
        $time = time();

        $params += [
            'iss' => $host,
            'aud' => $host,
            'iat' => $time,
            'nbf' => $time,
            'exp' => $time + config('session')['expire']
        ];
        $params['jti'] = compact('id', 'type');
        $token = JWT::encode($params, Config::get('app.app_key', 'default'));

        return compact('token', 'params');
    }

    /**
     * @param string $jwt
     * @return array
     *
     * @throws UnexpectedValueException     Provided JWT was invalid
     * @throws SignatureInvalidException    Provided JWT was invalid because the signature verification failed
     * @throws BeforeValidException         Provided JWT is trying to be used before it's eligible as defined by 'nbf'
     * @throws BeforeValidException         Provided JWT is trying to be used before it's been created as defined by 'iat'
     * @throws ExpiredException             Provided JWT has since expired, as defined by the 'exp' claim
     *
     */
    public static function parseToken(string $jwt): array {
        JWT::$leeway = 60;
        if (empty($jwt)) {
            exception('登录已过期 token empty', 410001);
        }
        $data = JWT::decode($jwt, Config::get('app.app_key', 'default'), array('HS256'));
        if (empty($data)) {
            exception('登录已过期', 410001);
        }
        //获取最新的资料
        if (SessionService::instance()->get($jwt) == false) {
            exception('登录已过期  token empty', 410001);
        }

        return [SessionService::instance()->online_data['user'], $data->jti->type];
    }

}
